# -*- coding: utf-8 -*-
import datetime
import os

from PIL import Image, ImageDraw, ImageFont

'''
图片拼接代码
'''


class ImgPiece(object):

    def __init__(self) -> None:
        super().__init__()
        self.heiti_55_font = ImageFont.truetype('/System/Library/Fonts/STHeiti Medium.ttc', 55)

    def imgPiece(self, img_path):
        img_list = os.listdir(img_path)
        img_source = [_ for _ in img_list if _.endswith('jpg')]

        count = len(img_source)
        col = 8
        row = int(count / col) if count % col == 0 else int(count / col) + 1
        img_width, img_height = Image.open(os.path.join(img_path, img_source[0])).size

        print('properties: count, col, row, width, height', count, col, row, img_width, img_height)

        image = Image.new('RGBA', (col * img_width, row * img_height))
        x, y = 0, 0

        for fn in img_source:
            try:
                wait_img_path = os.path.join(img_path, fn)
                img = Image.open(wait_img_path)

            except IOError as ioe:
                print('Error', ioe)
            else:
                img = img.resize((img_width, img_height), Image.ANTIALIAS)
                image.paste(img, (x * img_width, y * img_height))
                if x % col == col - 1:
                    x = 0
                    y += 1
                else:
                    x += 1

        draw = ImageDraw.Draw(image, 'RGBA')
        # draw.textsize('test test', self.heiti_55_font)
        draw.text((col * img_width - 400, row * img_height - 80), '三上优亚作品集', '#ff00e9', self.heiti_55_font)

        targetname = '../{}_OUT_{}.png'.format(col, datetime.datetime.now().strftime('%Y%m%d%H%M%S%s'))
        target_path = os.path.join(img_path, targetname)
        print('output path', target_path)
        image.save(target_path, 'png')


if __name__ == '__main__':
    ip = ImgPiece()
    root = '/data/code/scrapy/demoi/mansite/img/三上悠亜'
    ip.imgPiece(root)
